/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年10月10日
 *******************************************************************************/

package com.hualife.md.team.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hualife.md.constants.APIConstants;
import com.hualife.md.team.dao.ex.entity.TeamMembersInfo;
import com.hualife.md.team.dao.ex.entity.TeamQuery;
import com.hualife.md.team.dao.mybatis.entity.TeamInfo;
import com.hualife.md.team.dto.manage.MembersInfoRequestDTO;
import com.hualife.md.team.dto.manage.TeamChangeRequestDTO;
import com.hualife.md.team.dto.manage.TeamFoundationRequestDTO;
import com.hualife.md.team.dto.manage.TeamInfoRequestDTO;
import com.hualife.md.team.dto.manage.TeamManagerTransitionRequestDTO;
import com.hualife.md.team.dto.manage.TeamMemberManageRequestDTO;
import com.hualife.md.team.dto.query.MembersInfoResponseDTO;
import com.hualife.md.team.dto.query.TeamQueryRequestDTO;
import com.hualife.md.team.dto.query.TeamQueryResponseDTO;
import com.hualife.md.team.service.ITeamManageService;
import com.hualife.md.team.service.ITeamQueryService;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.exception.SysException;
import com.hualife.support.util.JsonUtil;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@RestController
@RequestMapping(value = "/api/v1")
public class TeamController {
	private static final Logger logger = LoggerFactory
			.getLogger(TeamController.class);

	@Autowired
	private ITeamQueryService teamQueryService;
	@Autowired
	private ITeamManageService teamManageService;

	@RequestMapping(value = "/team/query", method = RequestMethod.GET)
	public Map<String, Object> teamQuery(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*"); // 解决前后端跨域问题
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim())) {
			throw new BusinessException("查询条件不允许为空！");
		}

		try {
			TeamQueryRequestDTO requestDTO = (TeamQueryRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data, TeamQueryRequestDTO.class);
			String teamId = requestDTO.getTeamId();
			if (teamId == null || "".equals(teamId.trim())) {
				throw new BusinessException("查询条件不允许为空！");
			} else {
				teamId = teamId.trim();
			}
			String organizationCode = requestDTO.getOrganizationCode();
			if(organizationCode != null) {
				organizationCode = organizationCode.trim();
			}
			String currentLevel = requestDTO.getCurrentLevel();
			if(currentLevel != null) {
				currentLevel = currentLevel.trim();
			}
			TeamInfo teaminfo = teamQueryService.selectTeamInfo(teamId);
			if (teaminfo == null) {
				throw new BusinessException("查不到该群组的信息，请确认查询条件是否正确！");
			}

			TeamQuery teamQuery = new TeamQuery();
			teamQuery.setTeamId(teamId);
			teamQuery.setOrganizationCode(organizationCode);
			teamQuery.setCurrentLevel(currentLevel);
			
			List<TeamMembersInfo> members = teamQueryService
					.selectMembersInfoByTeamId(teamQuery);
			int totalnumber = teamQueryService
					.selectTotalMembersByTeamId(teamQuery);

			TeamQueryResponseDTO responseDTO = new TeamQueryResponseDTO();
			responseDTO.setTeamId(teamId.trim());
			responseDTO.setTeamName(teaminfo.getTeamName());
			responseDTO.setTotalNumber(totalnumber);

			List<MembersInfoResponseDTO> membersDTO = new ArrayList<MembersInfoResponseDTO>();
			for (TeamMembersInfo member : members) {
				MembersInfoResponseDTO memberDTO = new MembersInfoResponseDTO();
				memberDTO.setMemberId(member.getMemberId());
				memberDTO.setMemberName(member.getMemberName());
				memberDTO.setMemberType(member.getMemberType());
				membersDTO.add(memberDTO);
			}
			responseDTO.setMembersInfo(membersDTO);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "查询成功！");
			map.put("data", JsonUtil.CamelBean2SnakeJson(responseDTO));
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}

	@RequestMapping(value = "/team/foundation", method = RequestMethod.POST)
	public Map<String, Object> teamFoundation(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim())) {
			throw new BusinessException("请求条件不允许为空！");
		}

		try {
			TeamFoundationRequestDTO requestDTO = (TeamFoundationRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data, TeamFoundationRequestDTO.class);
			String teamCreator = requestDTO.getTeamCreator();
			String teamName = requestDTO.getTeamName();
			List<MembersInfoRequestDTO> membersInfo = requestDTO
					.getMembersInfo();
			if (teamCreator == null || "".equals(teamCreator.trim())) {
				throw new BusinessException("群组创建人不允许为空！");
			}
			if (teamName == null || "".equals(teamName.trim())) {
				throw new BusinessException("群组名称不允许为空！");
			}
			if (membersInfo == null || membersInfo.size() < 2) {
				throw new BusinessException("创建群组时至少需要加入2名组员！");
			}
			TeamInfo teaminfoReq = new TeamInfo();
			teaminfoReq.setTeamManager(teamCreator.trim());
			teaminfoReq.setTeamName(teamName.trim());
			
			List<TeamMembersInfo> teamMembersList = new ArrayList<TeamMembersInfo>();
			for (MembersInfoRequestDTO member : membersInfo) {
				if (member == null || member.getMemberId() == null || "".equals(member.getMemberId().trim())) {
					throw new BusinessException("用户编码不允许为空！");
				}

				TeamMembersInfo teamMember = new TeamMembersInfo();
				
				teamMember.setMemberId(member.getMemberId().trim());
				teamMembersList.add(teamMember);
			}
			String teamId = teamManageService.teamFoundation(teaminfoReq, teamMembersList);
			TeamInfo teaminfo = teamQueryService.selectTeamInfo(teamId);
			if (teaminfo == null) {
				throw new BusinessException("查不到该群组的信息，请确认查询条件是否正确！");
			}

			TeamQuery teamQuery = new TeamQuery();
			teamQuery.setTeamId(teamId);
			List<TeamMembersInfo> members = teamQueryService
					.selectMembersInfoByTeamId(teamQuery);
			int totalnumber = teamQueryService
					.selectTotalMembersByTeamId(teamQuery);

			TeamQueryResponseDTO responseDTO = new TeamQueryResponseDTO();
			responseDTO.setTeamId(teamId);
			responseDTO.setTeamName(teaminfo.getTeamName());
			responseDTO.setTotalNumber(totalnumber);

			List<MembersInfoResponseDTO> membersDTO = new ArrayList<MembersInfoResponseDTO>();
			for (TeamMembersInfo member : members) {
				MembersInfoResponseDTO memberDTO = new MembersInfoResponseDTO();
				memberDTO.setMemberId(member.getMemberId());
				memberDTO.setMemberName(member.getMemberName());
				memberDTO.setMemberType(member.getMemberType());
				membersDTO.add(memberDTO);
			}
			responseDTO.setMembersInfo(membersDTO);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "查询成功！");
			map.put("data", JsonUtil.CamelBean2SnakeJson(responseDTO));
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/foundation交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/foundation交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/foundation交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/api/v1/team/foundation交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}

	@RequestMapping(value = "/team/member/addition", method = RequestMethod.POST)
	public Map<String, Object> teamMemberAddition(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim())) {
			throw new BusinessException("请求条件不允许为空！");
		}

		try {
			TeamMemberManageRequestDTO requestDTO = (TeamMemberManageRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data, TeamMemberManageRequestDTO.class);
			String operator = requestDTO.getOperator();
			String teamId = requestDTO.getTeamId();
			List<MembersInfoRequestDTO> membersInfoList = requestDTO
					.getMembersInfo();
			if (operator == null || "".equals(operator.trim())) {
				throw new BusinessException("操作人不允许为空！");
			}
			if (teamId == null || "".equals(teamId.trim())) {
				throw new BusinessException("群组ID不允许为空！");
			}
			if (membersInfoList == null || membersInfoList.size() < 1) {
				throw new BusinessException("请传入要添加的用户数据！");
			}
			
			List<TeamMembersInfo> teamMembersList = new ArrayList<TeamMembersInfo>();
			for(MembersInfoRequestDTO membersInfo:membersInfoList) {
				TeamMembersInfo teamMembersInfo = new TeamMembersInfo();
				teamMembersInfo.setMemberId(membersInfo.getMemberId().trim());
				teamMembersList.add(teamMembersInfo);
			}
			teamManageService.teamMemberAddition(operator.trim(), teamId.trim(), teamMembersList);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "群成员添加成功！");
			map.put("data", "{}");
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}

	@RequestMapping(value = "/team/member/remove", method = RequestMethod.POST)
	public Map<String, Object> teamMemberRemove(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim())) {
			throw new BusinessException("请求条件不允许为空！");
		}

		try {
			TeamMemberManageRequestDTO requestDTO = (TeamMemberManageRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data, TeamMemberManageRequestDTO.class);
			String operator = requestDTO.getOperator();
			String teamId = requestDTO.getTeamId();
			List<MembersInfoRequestDTO> membersInfoList = requestDTO
					.getMembersInfo();
			if (operator == null || "".equals(operator.trim())) {
				throw new BusinessException("操作人不允许为空！");
			}
			if (teamId == null || "".equals(teamId.trim())) {
				throw new BusinessException("群组ID不允许为空！");
			}
			if (membersInfoList == null || membersInfoList.size() < 1) {
				throw new BusinessException("请传入要被删除的用户数据！");
			}
			
			List<TeamMembersInfo> teamMembersList = new ArrayList<TeamMembersInfo>();
			for(MembersInfoRequestDTO membersInfo:membersInfoList) {
				TeamMembersInfo teamMembersInfo = new TeamMembersInfo();
				teamMembersInfo.setMemberId(membersInfo.getMemberId().trim());
				teamMembersList.add(teamMembersInfo);
			}
			teamManageService.teamMemberRemove(operator.trim(), teamId.trim(), teamMembersList);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "群成员移除成功！");
			map.put("data", "{}");
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/remove交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/remove交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/remove交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}

	@RequestMapping(value = "/team/change", method = RequestMethod.POST)
	public Map<String, Object> teamChange(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim())) {
			throw new BusinessException("请求条件不允许为空！");
		}

		try {
			TeamChangeRequestDTO requestDTO = (TeamChangeRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data, TeamChangeRequestDTO.class);
			String operator = requestDTO.getOperator();
			String teamId = requestDTO.getTeamId();
			TeamInfoRequestDTO teamInfo = requestDTO.getTeamInfo();
			if (operator == null || "".equals(operator.trim())) {
				throw new BusinessException("操作人不允许为空！");
			}
			if (teamId == null || "".equals(teamId.trim())) {
				throw new BusinessException("群组ID不允许为空！");
			}
			if (teamInfo == null) {
				throw new BusinessException("待修改信息不允许为空！");
			}
			String teamName = teamInfo.getTeamName();
			if (teamName == null || "".equals(teamName.trim())) {
				throw new BusinessException("群组名称不允许为空！");
			}
			TeamInfo teaminfo = new TeamInfo();
			teaminfo.setTeamId(Integer.parseInt(teamId.trim()));
			teaminfo.setTeamName(teamName.trim());
			teaminfo.setUpdateUser(operator.trim());
			teamManageService.teamChange(teaminfo);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "群组信息更改成功！");
			map.put("data", "{}");
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/change交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/change交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/change交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}

	@RequestMapping(value = "/team/manager/transition", method = RequestMethod.POST)
	public Map<String, Object> teamManagerTransition(
			HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim())) {
			throw new BusinessException("请求条件不允许为空！");
		}

		try {
			TeamManagerTransitionRequestDTO requestDTO = (TeamManagerTransitionRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data,
							TeamManagerTransitionRequestDTO.class);
			String operator = requestDTO.getOperator();
			String teamId = requestDTO.getTeamId();
			String newManager = requestDTO.getNewManager();
			if (operator == null || "".equals(operator.trim())) {
				throw new BusinessException("操作人不允许为空！");
			}
			if (teamId == null || "".equals(teamId.trim())) {
				throw new BusinessException("群组ID不允许为空！");
			}
			if (newManager == null || "".equals(newManager.trim())) {
				throw new BusinessException("管理员权限被转交人不允许为空！");
			}
			TeamInfo teaminfo = new TeamInfo();
			teaminfo.setTeamId(Integer.parseInt(teamId.trim()));
			teaminfo.setTeamManager(newManager.trim());
			teaminfo.setUpdateUser(operator.trim());
			teamManageService.teamManagerTransition(teaminfo);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "管理员权限移交成功！");
			map.put("data", "{}");
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/manager/transition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/manager/transition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/team/manager/transition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/api/v1/team/member/addition交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}
}

/*
 * 修改历史 $Log$
 */